/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.bpm.engine.impl.bpmn.behavior;

import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.base.Strings;
import com.je.bpm.core.model.BpmnModel;
import com.je.bpm.core.model.config.task.assignment.TaskAssigneeConfigImpl;
import com.je.bpm.core.model.task.KaiteCandidateUserTask;
import com.je.bpm.engine.ActivitiException;
import com.je.bpm.engine.ActivitiIllegalArgumentException;
import com.je.bpm.engine.DynamicBpmnConstants;
import com.je.bpm.engine.delegate.DelegateExecution;
import com.je.bpm.engine.delegate.Expression;
import com.je.bpm.engine.delegate.TaskListener;
import com.je.bpm.engine.delegate.event.ActivitiEventDispatcher;
import com.je.bpm.engine.delegate.event.ActivitiEventType;
import com.je.bpm.engine.delegate.event.impl.ActivitiEventBuilder;
import com.je.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl;
import com.je.bpm.engine.impl.context.Context;
import com.je.bpm.engine.impl.el.ExpressionManager;
import com.je.bpm.engine.impl.interceptor.CommandContext;
import com.je.bpm.engine.impl.persistence.entity.ExecutionEntity;
import com.je.bpm.engine.impl.persistence.entity.TaskEntity;
import com.je.bpm.engine.impl.persistence.entity.TaskEntityManager;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collection;
import java.util.List;

import static java.util.Arrays.asList;

/**
 * 候选节点行为
 */
public class KaiteCandidateUserTaskActivityBehavior extends KaiteBaseUserTaskActivityBehavior {

    private static final Logger logger = LoggerFactory.getLogger(KaiteCandidateUserTaskActivityBehavior.class);

    private KaiteCandidateUserTask kaiteCandidateUserTask;

    public KaiteCandidateUserTaskActivityBehavior(KaiteCandidateUserTask kaiteCandidateUserTask) {
        this.kaiteCandidateUserTask = kaiteCandidateUserTask;
        multiInstanceActivityBehavior = null;
    }

    @Override
    public void execute(DelegateExecution execution) {
        CommandContext commandContext = Context.getCommandContext();
        TaskEntityManager taskEntityManager = commandContext.getTaskEntityManager();
        TaskEntity task = taskEntityManager.create();
        ExecutionEntity executionEntity = (ExecutionEntity) execution;
        task.setExecution(executionEntity);
        task.setTaskDefinitionKey(kaiteCandidateUserTask.getId());
        task.setBusinessKey(executionEntity.getProcessInstanceBusinessKey());
        String activeTaskName;
        String activeTaskDescription;
        String activeTaskCategory;
        ProcessEngineConfigurationImpl processEngineConfiguration = Context.getProcessEngineConfiguration();
        BpmnModel bpmnModel = processEngineConfiguration.getRepositoryService().getBpmnModel(executionEntity.getProcessDefinitionId());
        Object assigneeUser = execution.getVariable(kaiteCandidateUserTask.getId());
        String strAssigneeUser = "";
        if (assigneeUser == null) {
            TaskAssigneeConfigImpl taskAssigneeConfig = kaiteCandidateUserTask.getTaskAssigneeConfig();
            if (Strings.isNullOrEmpty(executionEntity.getVariable(kaiteCandidateUserTask.getId(), String.class))) {
                strAssigneeUser = getUserIds(bpmnModel, kaiteCandidateUserTask, commandContext, taskAssigneeConfig, execution, task.getTaskDefinitionKey());
            } else {
                strAssigneeUser = executionEntity.getVariable(kaiteCandidateUserTask.getId(), String.class);
            }
        } else {
            strAssigneeUser = (String) assigneeUser;
        }
        List<String> userIds = asList(strAssigneeUser.split(","));
        validatePersonnelClearance(userIds, bpmnModel, task.getTaskDefinitionKey());
        List<String> activeTaskCandidateUsers = userIds;
        List<String> activeTaskCandidateGroups = null;


        ExpressionManager expressionManager = processEngineConfiguration.getExpressionManager();
        if (Context.getProcessEngineConfiguration().isEnableProcessDefinitionInfoCache()) {
            ObjectNode taskElementProperties = Context.getBpmnOverrideElementProperties(kaiteCandidateUserTask.getId(), execution.getProcessDefinitionId());
            activeTaskName = getActiveValue(kaiteCandidateUserTask.getName(), DynamicBpmnConstants.USER_TASK_NAME, taskElementProperties);
            activeTaskDescription = getActiveValue(kaiteCandidateUserTask.getDocumentation(), DynamicBpmnConstants.USER_TASK_DESCRIPTION, taskElementProperties);
            activeTaskCategory = getActiveValue(kaiteCandidateUserTask.getCategory(), DynamicBpmnConstants.USER_TASK_CATEGORY, taskElementProperties);
        } else {
            activeTaskName = kaiteCandidateUserTask.getName();
            activeTaskDescription = kaiteCandidateUserTask.getDocumentation();
            activeTaskCategory = kaiteCandidateUserTask.getCategory();
        }

        if (StringUtils.isNotEmpty(activeTaskName)) {
            String name;
            try {
                name = (String) expressionManager.createExpression(activeTaskName).getValue(execution);
            } catch (ActivitiException e) {
                name = activeTaskName;
                logger.warn("property not found in task name expression " + e.getMessage());
            }
            task.setName(name);
        }

        if (StringUtils.isNotEmpty(activeTaskDescription)) {
            String description;
            try {
                description = (String) expressionManager.createExpression(activeTaskDescription).getValue(execution);
            } catch (ActivitiException e) {
                description = activeTaskDescription;
                logger.warn("property not found in task description expression " + e.getMessage());
            }
            task.setDescription(description);
        }

        if (StringUtils.isNotEmpty(activeTaskCategory)) {
            final Object category = expressionManager.createExpression(activeTaskCategory).getValue(execution);
            if (category != null) {
                if (category instanceof String) {
                    task.setCategory((String) category);
                } else {
                    throw new ActivitiIllegalArgumentException("Category expression does not resolve to a string: " + activeTaskCategory);
                }
            }
        }

        task.setAppVersion(executionEntity.getProcessInstance().getAppVersion());
        taskEntityManager.insert(task, executionEntity);
        task.setVariablesLocal(calculateInputVariables(execution));


        JSONObject variableObj = handleBaseUserTaskConfig(kaiteCandidateUserTask, task, expressionManager, bpmnModel);
        task.setVariableLocal(TASK_GLOBAL_VAR, variableObj.toJSONString());
        boolean skipUserTask = false;
//        if (StringUtils.isNotEmpty(activeTaskSkipExpression)) {
//            Expression skipExpression = expressionManager.createExpression(activeTaskSkipExpression);
//            skipUserTask = SkipExpressionUtil.isSkipExpressionEnabled(execution, skipExpression) && SkipExpressionUtil.shouldSkipFlowElement(execution, skipExpression);
//        }

        // Handling assignments need to be done after the task is inserted, to have an id
        if (!skipUserTask) {
            handleAssignments(activeTaskCandidateUsers, activeTaskCandidateGroups, task, expressionManager, execution);
        }

        processEngineConfiguration.getListenerNotificationHelper().executeTaskListeners(task, TaskListener.EVENTNAME_CREATE);

        // All properties set, now fire events
        if (Context.getProcessEngineConfiguration().getEventDispatcher().isEnabled()) {
            ActivitiEventDispatcher eventDispatcher = Context.getProcessEngineConfiguration().getEventDispatcher();
            eventDispatcher.dispatchEvent(ActivitiEventBuilder.createEntityEvent(ActivitiEventType.TASK_CREATED, task));
            if (task.getAssignee() != null) {
                eventDispatcher.dispatchEvent(ActivitiEventBuilder.createEntityEvent(ActivitiEventType.TASK_ASSIGNED, task));
            }
        }

        for (String userId : userIds) {
            addUpcomingInfo(bpmnModel, execution, userId, task, false);
        }
        if (!(variableObj.containsKey("skip")) || !(variableObj.getBoolean("skip"))) {
            if (Context.getCommandContext().getAttribute(SUBMIT_IS_GATEWAY) == null) {
                //添加审批告知
                addApprovalNotice(commandContext, execution, task);
            }
        }
        //自动传阅
        automaticCirculation(task, bpmnModel);

        if (skipUserTask) {
            taskEntityManager.deleteTask(task, null, false, false);
            leave(execution);
        }
    }

    protected void handleAssignments(List<String> candidateUsers, List<String> candidateGroups, TaskEntity task, ExpressionManager expressionManager, DelegateExecution execution) {
        if (candidateGroups != null && !candidateGroups.isEmpty()) {
            for (String candidateGroup : candidateGroups) {
                Expression groupIdExpr = expressionManager.createExpression(candidateGroup);
                Object value = groupIdExpr.getValue(execution);
                if (value instanceof String) {
                    List<String> candidates = extractCandidates((String) value);
                    task.addCandidateGroups(candidates);
                } else if (value instanceof Collection) {
                    task.addCandidateGroups((Collection) value);
                } else {
                    throw new ActivitiIllegalArgumentException("Expression did not resolve to a string or collection of strings");
                }
            }
        }

        if (candidateUsers != null && !candidateUsers.isEmpty()) {
            for (String candidateUser : candidateUsers) {
                Expression userIdExpr = expressionManager.createExpression(candidateUser);
                Object value = userIdExpr.getValue(execution);
                if (value instanceof String) {
                    List<String> candidates = extractCandidates((String) value);
                    task.addCandidateUsers(candidates);
                } else if (value instanceof Collection) {
                    task.addCandidateUsers((Collection) value);
                } else {
                    throw new ActivitiException("Expression did not resolve to a string or collection of strings");
                }
            }
        }
    }

    /**
     * Extract a candidate list from a string.
     *
     * @param str
     * @return
     */
    protected List<String> extractCandidates(String str) {
        return asList(str.split("[\\s]*,[\\s]*"));
    }

}
